package sample2.provider.dml;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;

/**
 * @author YUN
 */
public class SQLQueryBuilder extends SQLBuilder {
	private List<String> mProjections = new ArrayList<String>();
	private SQLWhereBuilder mWhere;
	private List<String> mSortOrders = new ArrayList<String>();
	private int mLimit;
	private int mOffset;
	public SQLQueryBuilder(Uri uri) {
		super(uri);
	}
	public void addProjection(String projection) {
		mProjections.add(projection);
	}
	public void setWhere(SQLWhereBuilder where) {
		mWhere = where;
	}
	public void addSortOrder(String sortOrder) {
		mSortOrders.add(sortOrder);
	}
	public void addSortOrderDesc(String sortOrder) {
		addSortOrder(sortOrder + " DESC ");
	}
	public void setLimit(int limit) {
		mLimit = limit;
	}
	public void setOffset(int offset) {
		mOffset = offset;
	}
	public void setLimitOffset(int limit, int offset) {
		setLimit(limit);
		setOffset(offset);
	}
	/**
	 * <pre>
	 * ...
	 * SQLQueryBuilder sql = new SQLQueryBuilder(uri);
	 * sql.addProjection("columnName");
	 * sql.addWhere("_id", "10");
	 * sql.addSortOrder("_id");
	 * sql.setLimit(10);
	 * sql.setOffset(100);
	 * Cursor cursor = sql.query(getContentResolver());
	 * ...
	 * </pre>
	 * 
	 * @param contentResolver
	 * @return cursor
	 */
	public Cursor query(ContentResolver contentResolver) {
		String[] projection = null;
		String selection = null;
		String[] selectionArgs = null;
		String sortOrder = null;

		// SELECTION ~
		if (!mProjections.isEmpty()) {
			projection = mProjections.toArray(new String[] {});
		}

		// WHERE ~ AND ~
		if (mWhere != null) {
			selection = mWhere.getWhere();
			selectionArgs = mWhere.getSelectionArgs();
		}

		// ORDER BY ~
		if (!mSortOrders.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			int len = mSortOrders.size();
			for (int i = 0; i < len; i++) {
				// sortOrder
				sb.append(mSortOrders.get(i));
				// add comma
				if (i < len - 1) {
					sb.append(", ");
				}

			}
			sortOrder = sb.toString();
		}

		// LIMIT ~ OFFSET ~
		if (0 < mLimit) {
			// add limit
			sortOrder += " " + mLimit + " OFFSET " + mOffset;
		}

		return contentResolver.query(mUri, projection, selection, selectionArgs, sortOrder);
	}
}
